<!--上传文件-->
<script setup>
import {ElIcon,ElInputTag, ElUpload, ElButtonGroup, ElButton, ElNotification, ElSpace, ElText, ElInput} from "element-plus"
import { UploadFilled } from '@element-plus/icons-vue';
import {useRouter} from "vue-router"
import {h, ref} from "vue";
import {statusCode,IP,Port} from "@/utils/baseInfo.js"
import uploadStore from "@/store/upload.js"
const store = uploadStore();
const router = useRouter();

const uploadURL = `http://${IP}:${Port}/upload`
const showDrawer = ref(false); // 显示记录抽屉
const showUploadDrawer = ref(false); // 显示上传抽屉
// 抽屉中显示的数据
const gridData = ref([
  // {
  //   id:0,
  //   filename:"文件名",,
  //   lastModifiedDate:"",
  //   status:"success",
  //   reason:"上传成功"
  // }
]) // 记录抽屉的表格
const uploadData = ref([
  // {
  //   file:"文件名",
  //   tag:"1",
  //   description:"12345"
  // }
]) // 上传抽屉的表格

// 手动提交函数
const data = ref({}); // 上传文件附带的req.body参数
const uploadFiles = ref();
const submitFiles = ()=>{  // 发送文件的函数
  uploadFiles.value.submit()
};

// 上传状态控制钩子函数
const beforeUpload= (rawFile) => {

  const {uid,lastModifiedDate,name} = rawFile;
  let ext = name.split(".");
  ext = ext[ext.length-1].toUpperCase();

  if(store.allowExt.includes(ext)) {
    data.value["uid"] = uid;
    data.value["filename"] = name;
    return true
  }else{
    // 设置一个延迟，保证通知不被覆盖
    setTimeout(()=>{
      ElNotification({
        title:"禁止的后缀",
        message:h('div', { style: 'display:flex;flex-direction:column;align-items:start;justify-content:flex-start;' },
            `上传失败:${rawFile.name}`
        ),
        type:"warning",
      });
    })
    // 把信息加入侧边栏
    gridData.value.push({
      id:uid,
      filename:name,
      Date:lastModifiedDate.toLocaleString(),
      status:"失败",
      reason:"非法后缀"
    })
    return false
  }
}
const uploadSuccess = (res,file) => {
  const { uid,lastModifiedDate,name } = file.raw;
  console.log(res)
  ElNotification({
    title: '上传成功',
    duration:5000,
    message: h('div', { style: 'display:flex;flex-direction:column;align-items:start;justify-content:flex-start;' }, [
      h('div', {},`文件名:${file.name}`),h('div', {},`返回信息:${res.message}`),
    ]),
    type:"success"
  });
  gridData.value.push({
    id:uid,
    filename:name,
    Date:lastModifiedDate.toLocaleString(),
    status:"成功",
    reason:"",
  });
  store.updateFlash[res.type]=true;
  let uploadDataList = [];
  uploadData.value.map((item,index)=>{
    if(item.uid===uid)uploadDataList.push(index);
  })
  for (let i = 0; i < uploadDataList.length; i++) {
    uploadDataList.splice(uploadDataList[i],1)
  }
}
const uploadError = (error,file) => {
  const { uid,lastModifiedDate,name } = file.raw;
  ElNotification({
    title: '上传失败',
    duration:5000,
    message: h('div', { style: 'display:flex;flex-direction:column;align-items:start;justify-content:flex-start;' }, [
        h('div', {},`文件名:${file.name}`),h('div', {},`错误信息:${statusCode[error.status]}`),
    ]),
    type:"error"
  });
  // 添加成功记录
  gridData.value.push({
    id:uid,
    filename:name,
    Date:lastModifiedDate.toLocaleString(),
    status:"失败",
    reason:statusCode[error.status],
  })
  let uploadDataList = [];
  uploadData.value.map((item,index)=>{
    if(item.uid===uid)uploadDataList.push(index);
  })
  for (let i = 0; i < uploadDataList.length; i++) {
    uploadDataList.splice(uploadDataList[i],1)
  }
}
const uploadChange = (file,files)=>{
  // console.log("上传文件:",file)
  // console.log("总列表:",files)

  uploadData.value = files.map(item=>{
    let f = uploadData.value.find(value=>value.uid === item.uid)
    return f || {
      uid: item.uid,
      file:item.name,
      tags:[],
      description:"",
    }
  })
}
const uploadRemove = (file,files)=>{
  console.log(`文件移除:${file}`)
  console.log(`列表移除:${files}`)
}
</script>

<template>

    <div class="upload-demo">
      <el-upload
          ref="uploadFiles"
          :auto-upload="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          drag
          :action="uploadURL"
          :data="data"
          multiple
          :before-upload="beforeUpload"
          :on-change="uploadChange"
          :on-remove="uploadRemove"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          <em>点击</em> 此处或 <em>拖拽文件</em> 到此处上传
        </div>
        <template #tip>
          <div class="el-upload__tip">
            <el-text tag="b" type="warning">支持的扩展类型: <el-text type="info">wav, aac, mp3, mp4, jpg, jpeg, png, md</el-text></el-text>
            <el-button-group class="el-upload__btn-group">
              <el-button @click="()=>showDrawer=true">记录</el-button>
              <el-button @click="showUploadDrawer=true">上传</el-button>
              <el-button @click="()=>router.go(-1)">返回</el-button>
            </el-button-group>
          </div>
        </template>
      </el-upload>
    </div>

<!--  上传预览-->
    <el-drawer
      v-model="showUploadDrawer"
      title="上传预览"
      direction="rtl"
      size="50%"
  >
    <el-table :data="uploadData">
      <el-table-column type="index" width="50" />
      <el-table-column property="file" label="file" width="120" />
      <el-table-column property="tags" label="tags" width="200" >
        <template #default="scope">
          <el-input-tag v-model="scope.row.tags" :max="3" />
        </template>
      </el-table-column>
      <el-table-column property="description" label="description">
        <template #default="scope">
          <el-input
              v-model="scope.row.description"
              style="width: 90%"
              autosize
              type="textarea"
              placeholder="输入描述或者适配文本"
          />
        </template>
      </el-table-column>
    </el-table>
      <el-button @click="submitFiles">上传</el-button>
  </el-drawer>
<!--    上传记录-->
    <el-drawer
        v-model="showDrawer"
        title="上传记录"
        direction="rtl"
        size="50%"
    >
      <el-table :data="gridData">
        <el-table-column type="index" width="50" />
        <el-table-column property="id" label="ID" width="150" />
        <el-table-column property="filename" label="Filename"  />
        <el-table-column property="Date" label="Date" width="200"  />
        <el-table-column property="status" label="Status" width="100" />
        <el-table-column property="reason" label="Reason" width="150" />
      </el-table>
    </el-drawer>
</template>

<style scoped>
.upload-demo {
  width: 60%;
  margin: 0 auto ;
}
.el-upload__tip {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.el-upload__btn-group{
  width: 200px;
  text-align: center;
  display: flex;
  justify-content: space-around;
}
.el-upload__btn-group>.el-button {
  width: 90px;
}
</style>